package com.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.adapter.CollectLIstRecyclerViewAdapter;
import com.adapter.ReportLIstRecyclerViewAdapter;
import com.bean.CollectListBean;
import com.bean.ReportListBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.myapp.MyApp;
import com.myview.PullLoadMoreRecyclerView;
import com.util.DensityUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;
import com.xiaochun.hxhj.MyCourseActivity;
import com.xiaochun.hxhj.R;
import com.xiaochun.hxhj.WebviewActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class ReviewFragment extends Fragment implements View.OnClickListener {


    private Context mcontext;
    private MyApp myapp;
    private View view;
    private LinearLayout ll_mycollect;
    private TextView tv_mycollect;
    private View view_mycollect;
    private LinearLayout ll_myreport;
    private TextView tv_myreport;
    private View view_myreport;
    private PullLoadMoreRecyclerView collectlist_data;
    private PullLoadMoreRecyclerView reportlist_data;
    private SharedPreferences sharedPreferences;
    private String token;
    private int page = 1;
    private int pagecount = 20;
    private List<CollectListBean.DataBeanX.DataBean> collectlisttemp = new ArrayList<>();
    private List<CollectListBean.DataBeanX.DataBean> collectlist = new ArrayList<>();
    private View loadMoreShopView;
    private View notMoreShopView;
    private LinearLayoutManager layoutManagercollect;
    private LinearLayoutManager layoutManagerreport;
    private CollectLIstRecyclerViewAdapter collectadapter;
    private View bottomView;
    private ReportLIstRecyclerViewAdapter reporttadapter;
    private List<ReportListBean.DataBeanX.DataBean> reportlisttemp = new ArrayList<>();
    private List<ReportListBean.DataBeanX.DataBean> reportlist = new ArrayList<>();
    private View bottomView2;
    private LinearLayout loadLlay;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.e("Activity:", this.getClass().getName().toString());
        view = inflater.inflate(R.layout.fragment_review, container, false);
        mcontext = getActivity();
        myapp = (MyApp) mcontext.getApplicationContext();
        EventBus.getDefault().register(this);
        sharedPreferences = mcontext.getSharedPreferences("userinfo", Context.MODE_MULTI_PROCESS);
        token = sharedPreferences.getString("token", "");
        initView();

        initLin();
        getData();
        return view;

    }


    private void initView() {
        ll_mycollect = view.findViewById(R.id.ll_mycollect);
        tv_mycollect = view.findViewById(R.id.tv_mycollect);
        view_mycollect = view.findViewById(R.id.view_mycollect);
        ll_myreport = view.findViewById(R.id.ll_myreport);
        tv_myreport = view.findViewById(R.id.tv_myreport);
        view_myreport = view.findViewById(R.id.view_myreport);
        collectlist_data = view.findViewById(R.id.collectlist_data);
        collectadapter = new CollectLIstRecyclerViewAdapter(collectlist, mcontext, myapp);
        setHeader(collectlist_data);
        collectlist_data.setAdapter(collectadapter);
        collectlist_data.setLinearLayout();
        collectlist_data.setRefreshing(true);
        layoutManagercollect = (LinearLayoutManager) collectlist_data.getLayoutManager();
        collectlist_data.cancleAnimal();


        reportlist_data = view.findViewById(R.id.reportlist_data);
        reporttadapter = new ReportLIstRecyclerViewAdapter(reportlist, mcontext, myapp);
        setHeader2(reportlist_data);
        reportlist_data.setAdapter(reporttadapter);
        reportlist_data.setLinearLayout();
        reportlist_data.setRefreshing(true);
        layoutManagerreport = (LinearLayoutManager) reportlist_data.getLayoutManager();
        reportlist_data.cancleAnimal();


        loadMoreShopView = View.inflate(mcontext, R.layout.item_moredata, null);
        notMoreShopView = View.inflate(mcontext, R.layout.item_nodata, null);
        initTopView();
    }
    /**
     * 初始化头部控件
     */
    private void initTopView() {
        //加载更多
        loadLlay = (LinearLayout) bottomView.findViewById(R.id.llay_load);
    }
    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view) {

        //底部加载更多
        bottomView = LayoutInflater.from(mcontext).inflate(R.layout.main_bottom, view, false);
        collectadapter.setBottomView(bottomView);
    }
    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader2(PullLoadMoreRecyclerView view) {

        //底部加载更多
        bottomView2 = LayoutInflater.from(mcontext).inflate(R.layout.main_bottom, view, false);
        reporttadapter.setBottomView(bottomView2);
    }
    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String message = event.getMessage();
        Log.e("GTPCmessage--new--order", message);


    }

    private void initLin() {
        ll_mycollect.setOnClickListener(this);
        ll_myreport.setOnClickListener(this);

        collectlist_data.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }

            @Override
            public void onLoadMore() {
                if (collectlist.size() >= pagecount){
                    page++;
                    getData();
                }else{
                    collectlist_data.setPullLoadMoreCompleted();
                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });
        collectadapter.setOnItemClickListener(new CollectLIstRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int id = collectlist.get(position).getCourse_id();
                //TODO  进入我的课程详情
                Intent intent = new Intent(mcontext, MyCourseActivity.class);
                intent.putExtra("id",id+"");
                startActivity(intent);
            }
        });
        reportlist_data.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getReportData();
            }

            @Override
            public void onLoadMore() {
                if (reportlist.size() >= pagecount){
                    page++;
                    getReportData();
                }else{
                    reportlist_data.setPullLoadMoreCompleted();
                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });
        reporttadapter.setOnItemClickListener(new ReportLIstRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int id = reportlist.get(position).getId();
                Intent intent = new Intent(mcontext, WebviewActivity.class);
                intent.putExtra("url", myapp.getSiteurlweb() + "/#/studyReport?token=" + token+"&id="+id);
                startActivity(intent);
            }
        });
    }

    private void getData() {
        collectlisttemp.clear();
        token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/collect/myCollect";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("page", page+"");
        paramsMap.put("limit", pagecount+"");
        MyLog.e("我的收藏",token+"=token    ");
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONArray dataarr = data.getJSONArray("data");

                    collectlisttemp = new Gson().fromJson(dataarr.toString(), new TypeToken<List<CollectListBean.DataBeanX.DataBean>>() {
                    }.getType());

                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    private void getReportData() {
        reportlisttemp.clear();
        token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/collect/report";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("page", page+"");
        paramsMap.put("limit", pagecount+"");
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONArray dataarr = data.getJSONArray("data");

                    reportlisttemp = new Gson().fromJson(dataarr.toString(), new TypeToken<List<ReportListBean.DataBeanX.DataBean>>() {
                    }.getType());

                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }


    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    collectlist_data.setPullLoadMoreCompleted();
                    reportlist_data.setPullLoadMoreCompleted();
                    break;
                case 1:
                    ToastUtils.show(R.string.net_error);
                    collectlist_data.setPullLoadMoreCompleted();
                    reportlist_data.setPullLoadMoreCompleted();
                    break;
                case 2:

                    break;
                case 3:


                    break;
                case 4:
                    if (page == 1){
                        collectlist.clear();
                    }
                    collectlist.addAll(collectlisttemp);
                    collectadapter.setDatas(collectlist);
                    collectlist_data.setPullLoadMoreCompleted();
                    if (collectlisttemp.size() == 0){
                        page--;
                    }
                    loadLlay.removeAllViews();
                    if (collectlisttemp.size() < pagecount){
                        if (page > 1){
                            loadLlay.addView(notMoreShopView);
                        }
                    }else{
                        loadLlay.addView(loadMoreShopView);
                    }
                    break;
                case 5:
                    if (page == 1){
                        reportlist.clear();
                    }
                    reportlist.addAll(reportlisttemp);
                    reporttadapter.setDatas(reportlist);
                    reportlist_data.setPullLoadMoreCompleted();
                    if (reportlisttemp.size() == 0){
                        page--;
                    }
                    loadLlay.removeAllViews();
                    if (reportlisttemp.size() < pagecount){
                        if (page > 1){
                            loadLlay.addView(notMoreShopView);
                        }
                    }else{
                        loadLlay.addView(loadMoreShopView);
                    }
                    break;
                case 11:
                    sharedPreferences.edit().putString("user_id","").commit();
                    sharedPreferences.edit().putString("username","").commit();
                    sharedPreferences.edit().putString("nickname","").commit();
                    sharedPreferences.edit().putString("mobile","").commit();
                    sharedPreferences.edit().putString("avatar","").commit();
                    sharedPreferences.edit().putString("score","").commit();
                    sharedPreferences.edit().putString("student_id","").commit();
                    sharedPreferences.edit().putString("is_bind_wx","").commit();
                    sharedPreferences.edit().putString("token","").commit();
                    sharedPreferences.edit().putString("is_agent","").commit();
                    sharedPreferences.edit().putString("vip_expire","").commit();
                    sharedPreferences.edit().putString("is_vip","").commit();
                    collectlist_data.setPullLoadMoreCompleted();
                    reportlist_data.setPullLoadMoreCompleted();
                    break;
                case 12:

                    break;
            }
        }
    };

    private boolean islogin = false;

    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {
//        dm = new DisplayMetrics();
//        heightPixels = dm.heightPixels;
//        getWindowManager().getDefaultDisplay().getMetrics(dm);

        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        int width = dm.widthPixels;
        int heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度   " + width);
    }


    @Override
    public void onResume() {
        super.onResume();

        MyLog.e("首页", "onResume");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        MyLog.e("首页", "onHiddenChanged     " + hidden);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_mycollect:
                if (DensityUtil.isFastDoubleClick()){
                    return;
                }
                page = 1;
                getData();
                view_mycollect.setVisibility(View.VISIBLE);
                tv_mycollect.setTextSize(15);
                view_myreport.setVisibility(View.INVISIBLE);
                tv_myreport.setTextSize(12);
                collectlist_data.setVisibility(View.VISIBLE);
                reportlist_data.setVisibility(View.GONE);
                break;
            case R.id.ll_myreport:
                if (DensityUtil.isFastDoubleClick()){
                    return;
                }
                page = 1;
                getReportData();
                view_mycollect.setVisibility(View.INVISIBLE);
                tv_mycollect.setTextSize(12);
                view_myreport.setVisibility(View.VISIBLE);
                tv_myreport.setTextSize(15);
                reportlist_data.setVisibility(View.VISIBLE);
                collectlist_data.setVisibility(View.GONE);
                break;
        }
    }
}
